import 'package:flutter/material.dart';
import 'package:flutter_demo/ui/graphQL_test/model/country.dart';
import 'package:flutter_demo/widgets/query_wrapper.dart';
///@date:  2024/1/11
///@author:  leisiyu
///@description:
class CountryListView extends StatefulWidget {
  const CountryListView({super.key});

  @override
  State<StatefulWidget> createState() => _CountryPageState();
}

class _CountryPageState extends State<CountryListView> {
  ///GraphQL查询语句
  final String query = '''
                      query Countries {
                          countries {
                            code
                            name
                            currency
                            emoji
                          }
                      }
                  ''';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('List of Countries'),
      ),
      body: QueryWrapper<Country>(
        queryString: query,
        contentBuilder: (data) => _buildList(data),
        dataParser: (data) => Country.fromJson(data),
      ),
    );
  }

  Widget _buildList(Country result) {
    return Container(
        alignment: Alignment.center,
        // 在这里创建一个Column widget作为子widget
        child: Container(
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            // 在Column widget中创建一个列表，包含多个子widget
            children: [
              // 在列表中创建一个Text widget，用于显示viewModel的message属性，如果该属性为空则显示空字符串
              const Text(""),
              SizedBox(
                  height: 550, // fixed height
                  child: _countriesView(result)),
            ],
          ),
        ));
  }

  ///listview demo
  ListView _countriesView(Country result) {
    return ListView.separated(
      itemCount: result.countries.length,
      scrollDirection: Axis.vertical,
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(result.countries[index].name),
          subtitle: Text('Currency: ${result.countries[index].currency}'),
          leading: Text(result.countries[index].emoji),
          onTap: () {
          },
        );
      },
      separatorBuilder: (context, index) {
        return const Divider();
      },
    );
  }
}
